﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using TM.QWeibo.Client.Helper;
using TM.QWeibo.Client;
using System.IO;
using System.Windows.Media.Imaging;
using Microsoft.Xna.Framework.Media;
using AviarySDK;
using System.Windows.Threading;
using System.Diagnostics;
using Microsoft.Phone.Info;
using Microsoft.Phone.Shell;
using TM.QWeibo.SDK.Objects;

namespace TM.QWeibo.Client.Tweet
{
    public partial class Add : PhoneApplicationPage
    {
        public Add()
        {
            InitializeComponent();
            tweetContent.Text = "";
            GC.Collect();
            this.ApplicationBar.BackgroundColor = (Color)App.Current.Resources["ApplicationBarBackgroundColor"];
        }


        #region 私有属性

        /// <summary>
        /// 是否显示选择表情或者话题或者提及
        /// </summary>
        private bool isShowPop { get; set; }

        DraftHelper draftHelper = new DraftHelper();

        /// <summary>
        /// 添加微博的类型
        /// </summary>
        private EAddTweetType _AddType { get; set; }

        /// <summary>
        /// 非新微博时的目标微博
        /// </summary>
        private TM.QWeibo.SDK.Objects.Tweet targetTweet { get; set; }

        private TM.QWeibo.SDK.Objects.TweetContent tweetContent = new SDK.Objects.TweetContent();

        /// <summary>
        /// 扩展数据，发私信时使用，内容为收信人name
        /// </summary>
        private string metaData { get; set; }

        #endregion

        #region 导航服务

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            tbWordCount.Text = string.Format("({0})", AppSetting.MaxTweetWordCount);

            FaceSelector.Selected = FaceImageSelected;
            UserSelector.Selected = UserSelected;
            HuatiSelector.Selected = HuatiSelected;

            if (NavigationContext.QueryString.ContainsKey(AppSetting.AddTweetTypeParameterKey))
            {
                var addTypeString = NavigationContext.QueryString[AppSetting.AddTweetTypeParameterKey];
                if (!string.IsNullOrWhiteSpace(addTypeString))
                {
                    //获取添加微博的类型
                    _AddType = (EAddTweetType)int.Parse(addTypeString);
                    if (_AddType != EAddTweetType.Add)
                    {
                        //设置标题
                        if (_AddType != EAddTweetType.Mention && _AddType != EAddTweetType.PrivateMessage)
                        {
                            if (_AddType == EAddTweetType.ReAdd)
                            {
                                tbTitle.Text = "转播微博";
                            }
                            else if (_AddType == EAddTweetType.Reply)
                            {
                                tbTitle.Text = "回复微博";
                            }
                            else
                            {
                                tbTitle.Text = "对话";
                            }

                            //设置按钮可用
                            this.ApplicationBar.Buttons.RemoveAt(1);//图片
                            this.ApplicationBar.MenuItems.RemoveAt(2);//清空图片
                            var _t = new SDK.Objects.Tweet();
                            if (Common.Isolated.Get<SDK.Objects.Tweet>(Helper.IsolatedHelper.TargetTweetKey, out _t))
                            {
                                targetTweet = _t;
                                if (targetTweet != null)
                                {
                                    //如果回复/转播的微博类型是回复/转播，在微博的内容上加入这条微博的内容
                                    if (_AddType != EAddTweetType.Comment && (targetTweet.Type == SDK.Objects.Tweet.ETweetType.Forward || targetTweet.Type == SDK.Objects.Tweet.ETweetType.Reply) && targetTweet.Source != null)
                                    {
                                        //if (!string.IsNullOrWhiteSpace(targetTweet.Origtext))
                                        //{
                                        txtContent.Text = "||@" + targetTweet.Name + "：" + targetTweet.Origtext;
                                        //}
                                        tbTargetTweet.Text = string.Format("{0}：{1}", targetTweet.Source.NickName, targetTweet.Source.Origtext);
                                    }
                                    else
                                    {
                                        tbTargetTweet.Text = string.Format("{0}：{1}", targetTweet.NickName, targetTweet.Origtext);
                                    }
                                }
                            }
                        }
                        else if (_AddType != EAddTweetType.PrivateMessage)
                        {
                            var name = NavigationContext.QueryString[AppSetting.AddTweetMetaParameterKey];
                            tbTitle.Text = "@" + name;
                            var str = "@" + name+" ";
                            //扩展内容2
                            if (NavigationContext.QueryString.ContainsKey(AppSetting.AddTweetSubMetaParameterKey))
                            {

                                str +=  HttpUtility.UrlDecode(NavigationContext.QueryString[AppSetting.AddTweetSubMetaParameterKey]);

                            }
                            txtContent.Text = str;
                            txtContent.SelectionStart = txtContent.Text.Length;
                            txtContent.Focus();
                        }
                        else
                        {
                            var name = NavigationContext.QueryString[AppSetting.AddTweetMetaParameterKey];
                            metaData = name;
                            tbTitle.Text = "私信：" + name;
                        }
                    }  
                }
            }

            if(_AddType==EAddTweetType.Add)
            {
                var draft = draftHelper.Get();
                if (!string.IsNullOrWhiteSpace(draft))
                {
                    txtContent.Text = draft;
                    txtContent.SelectionStart = txtContent.Text.Length;
                    txtContent.Focus();
                }
                if(draftHelper.TweetImage!=null)
                {
                    tweetContent.Image = draftHelper.TweetImage;
                    imgPhotoIcon.Visibility = Visibility.Visible;
                    ((ApplicationBarMenuItem)this.ApplicationBar.MenuItems[2]).IsEnabled = true;//清空图片
                }
            } 
        }


        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);

            if (_AddType == EAddTweetType.Add)
            {
                draftHelper.Save(txtContent.Text);
                if(tweetContent!=null && tweetContent.HasImage)
                {
                    draftHelper.TweetImage = tweetContent.Image;
                }
            }
        }


        #endregion


        #region 页面操作事件

        /// <summary>
        /// 选择图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPhoto_Click(object sender, EventArgs e)
        {
            var photoTask = new PhotoChooserTask { ShowCamera = true };
            photoTask.Completed += PhotoChooserTask_Completed;
            photoTask.Show();
        }

        private void PhotoChooserTask_Completed(object sender, PhotoResult e) {

            try
            {
                if (e.ChosenPhoto != null)
                {
                    ((ApplicationBarMenuItem)this.ApplicationBar.MenuItems[2]).IsEnabled=true;//清空图片
                    imgPhotoIcon.Visibility = Visibility.Visible;
                    if (string.IsNullOrWhiteSpace(tweetContent.Text)) {
                        txtContent.Text="#分享照片#";
                    }
                    tweetContent.Image = new SDK.Objects.UploadFile(e.OriginalFileName, Helper.ImageHelper.Compression(e.ChosenPhoto));
                    var features = new List<AviaryFeature>
                                       {
                                           AviaryFeature.Enhance,
                                           AviaryFeature.Effects,
                                           AviaryFeature.Orientation,
                                           AviaryFeature.Brightness,
                                           AviaryFeature.Sharpness,
                                           AviaryFeature.Whiten,
                                           AviaryFeature.Redeye,
                                           AviaryFeature.Blemish
                                       };
                    var aviaryTask = new AviaryTask(tweetContent.Image.FileStream,features,"52A6EF");
                    aviaryTask.Completed += AviaryTaskCompleted;
                    aviaryTask.Show();
                }
            }
            catch
            {
            }
        
        }

        void AviaryTaskCompleted(object sender, AviaryTaskResultArgs e)
        {
            if (e.AviaryResult == AviaryResult.OK)
            {
                var stream = new MemoryStream();
                e.PhotoResult.SaveJpeg(stream, e.PhotoResult.PixelWidth, e.PhotoResult.PixelHeight, 0, 100);
                stream.Seek(0, SeekOrigin.Begin);
                tweetContent.Image = new UploadFile(draftHelper.TweetImage.FileName, stream);
                draftHelper.TweetImage = tweetContent.Image;
            }
        }

        /// <summary>
        /// 发布微博
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            HideInputKeyboard();

            progressBar.IsIndeterminate = true;

            tweetContent.ClientIp = AppSetting.IpAddress;

            var isSyncToQzone= (bool)syncToQzone.IsChecked;

            if (_AddType == EAddTweetType.ReAdd)//转播
            {
                //二次转播
                if ((targetTweet.Type == SDK.Objects.Tweet.ETweetType.Forward || targetTweet.Type == SDK.Objects.Tweet.ETweetType.Reply) && targetTweet.Source != null)
                {
                    Dal.Tweet.Instance.ReAdd(targetTweet.Source.Id, tweetContent, PublishTweetEnd, isSyncToQzone);
                }
                else {
                    Dal.Tweet.Instance.ReAdd(targetTweet.Id, tweetContent, PublishTweetEnd, isSyncToQzone);
                }
            }
            else
            {
                if (tweetContent!=null && tweetContent.Text!=null && !string.IsNullOrWhiteSpace(tweetContent.Text) && tweetContent.Text.Length > 0 && tweetContent.Text.Length <= AppSetting.MaxTweetWordCount)
                {
                    if (_AddType == EAddTweetType.Add || _AddType==EAddTweetType.Mention)//新或提及
                    {

                        Dal.Tweet.Instance.Add(tweetContent, PublishTweetEnd, isSyncToQzone);
                    }
                    else if (_AddType == EAddTweetType.Reply)//回复
                    {
                        //二次回复
                        if ((targetTweet.Type == SDK.Objects.Tweet.ETweetType.Forward || targetTweet.Type == SDK.Objects.Tweet.ETweetType.Reply) && targetTweet.Source != null)
                        {
                            Dal.Tweet.Instance.Reply(targetTweet.Source.Id, tweetContent, PublishTweetEnd, isSyncToQzone);
                        }
                        else
                        {
                            Dal.Tweet.Instance.Reply(targetTweet.Id, tweetContent, PublishTweetEnd, isSyncToQzone);
                        }
                        
                    }
                    else if (_AddType == EAddTweetType.Comment) //对话
                    {
                        Dal.Tweet.Instance.Comment(targetTweet.Id, tweetContent, PublishTweetEnd, isSyncToQzone);
                    }
                    else
                    {
                        Dal.Message.Instance.Add(metaData, tweetContent, PublishTweetEnd);
                    }
                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                   {
                       progressBar.IsIndeterminate = false;
                       (new Helper.MessageBoxHelper()).Show("微博内容不能为空也不能大于" + AppSetting.MaxTweetWordCount, "温馨提示", this.LayoutRoot);
                   });
                }
            }
        }
        /// <summary>
        /// 发布微博结束回调
        /// </summary>
        /// <param name="rs"></param>
        private void PublishTweetEnd(bool rs) {

            if (rs && _AddType == EAddTweetType.Add) {

                draftHelper.Clear();

            }

            if (_AddType != EAddTweetType.PrivateMessage)
            {
                if (rs)
                {
                    targetTweet = null;

                    tweetContent = null;

                    Common.Isolated.Remove(Helper.IsolatedHelper.TargetTweetKey);

                    Dispatcher.BeginInvoke(() =>
                    {
                        txtContent.Text = "";
                        if (NavigationService.CanGoBack && !NavigationContext.QueryString.ContainsKey(AppSetting.IsQuickTweetParameterKey))
                        {
                            NavigationService.GoBack();
                        }
                        else
                        {
                            NavigationService.Navigate(new Uri(string.Format("/MainPage.xaml"), UriKind.Relative));
                        }
                    });
                }
                else
                {
                    Dispatcher.BeginInvoke(() =>
                   {
                       progressBar.IsIndeterminate = false;
                       (new Helper.MessageBoxHelper()).Show("发布失败，请重试。","提示", this.LayoutRoot);
                   });
                }
            }
            else {
                if (rs)
                {
                    tweetContent = null;
                    Dispatcher.BeginInvoke(() =>
                    {
                        txtContent.Text = "";
                        if (NavigationService.CanGoBack)
                        {
                            NavigationService.GoBack();
                        }
                        else {
                            NavigationService.Navigate(new Uri(string.Format("/MainPage.xaml"), UriKind.Relative));
                        }
                    });
                }
                else {
                    Dispatcher.BeginInvoke(() =>
                    {
                        progressBar.IsIndeterminate = false;
                        (new Helper.MessageBoxHelper()).Show("发信失败，请重试。","提示", this.LayoutRoot);
                    });
                }
            }
        }


        /// <summary>
        /// @
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMentions_Click(object sender, EventArgs e)
        {
            if (isShowPop) { return; }
            isShowPop = true;
            HideInputKeyboard();
            UserSelector.Show();
        }

        private void UserSelected(SDK.Objects.UserInfo user)
        {
            Dispatcher.BeginInvoke(() =>
            {
                isShowPop=false;
                InsertContent("@" + user.Name+" ");
                UserSelector.Hide();
                txtContent.Focus();
            });
        }

        /// <summary>
        /// 插入内容
        /// </summary>
        /// <param name="content"></param>
        public void InsertContent(string content) {
            Dispatcher.BeginInvoke(() => {
                //判断是否有选择内容，没有的在光标处插入，有替换选择的内容
                if (txtContent.SelectedText.Length < 0)
                {
                    txtContent.Select(txtContent.SelectionStart, txtContent.Text.Length - txtContent.SelectionStart);
                    txtContent.SelectedText = content + txtContent.SelectedText;
                    txtContent.SelectionStart += content.Length;
                }
                else {
                    txtContent.SelectedText = content;
                }
                txtContent.Focus();
            });
        }

        /// <summary>
        /// 插入表情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFace_Click(object sender, EventArgs e)
        {
            if (isShowPop) { return; }
            isShowPop = true;
            HideInputKeyboard();
            progressBar.IsIndeterminate = true;
            FaceSelector.Show(() =>
            {
                progressBar.IsIndeterminate = false;

            });
        }

        private void FaceImageSelected(string code)
        {
            Dispatcher.BeginInvoke(() =>
            {
                isShowPop = false;
                InsertContent(code);
                FaceSelector.Hide();
                txtContent.Focus();
            });
        }

        /// <summary>
        /// 插入话题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mTopic_Click(object sender, EventArgs e)
        {
            if (isShowPop) { return; }
            isShowPop = true;
            HideInputKeyboard();
            HuatiSelector.Show();
        }

        private void HuatiSelected(string huati) {
            Dispatcher.BeginInvoke(() =>
            {
                isShowPop = false;
                InsertContent(huati);
                HuatiSelector.Hide();
                txtContent.Focus();
            });

        }

        /// <summary>
        /// 清除文字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mClearText_Click(object sender, EventArgs e)
        {
            txtContent.Text = "";
            tweetContent.Text = "";
        }

        /// <summary>
        /// 清除图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void mClearPhoto_Click(object sender, EventArgs e)
        {
            imgPhotoIcon.Visibility = Visibility.Collapsed;
            tweetContent.Image = null;
            ((ApplicationBarMenuItem)this.ApplicationBar.MenuItems[2]).IsEnabled = false;//清空图片
        }

        /// <summary>
        /// 文本改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtContent_TextChanged(object sender, TextChangedEventArgs e)
        {
            tbWordCount.Text = string.Format("({0})", (AppSetting.MaxTweetWordCount - txtContent.Text.Length));
            if (tweetContent!=null)
            {
                tweetContent.Text = txtContent.Text;
            }
        }

        /// <summary>
        /// 隐藏输入法
        /// </summary>
        private void HideInputKeyboard() {

            Dispatcher.BeginInvoke(() => btnHelper.Focus());

        }

        #endregion

        private void txtContent_GotFocus(object sender, RoutedEventArgs e)
        {
            txtContent.BorderThickness = new Thickness(1);
            txtContent.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 189, 190, 189));
        }

        private void txtContent_LostFocus(object sender, RoutedEventArgs e)
        {
            txtContent.BorderThickness = new Thickness(1);
            txtContent.BorderBrush = new SolidColorBrush(Color.FromArgb(255, 189, 190, 189));
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (isShowPop)
            {
                isShowPop = false;
                FaceSelector.Hide();
                HuatiSelector.Hide();
                UserSelector.Hide();
                e.Cancel = true;
            }
            else {
                if (NavigationContext.QueryString.ContainsKey(AppSetting.IsQuickTweetParameterKey)) {
                    App.Quit();
                }
            }
        }

        #region 事件回调

        #endregion
    }
}
